package com.dyh.quickdemo.demos.UnsafeFunc;

import sun.misc.Unsafe;

import javax.annotation.processing.Completion;
import java.lang.reflect.Field;
import java.util.concurrent.CompletableFuture;

/*
@Author=Joey Wheeler
@Date=2020/10/26 16:45
*/
public class UnsafeFunDemo {
    private static final sun.misc.Unsafe UNSAFE;
    private static final long resultAddr;
    volatile String result;
    static {
        try {
            /**/
         //   final sun.misc.Unsafe u;
         //   UNSAFE = u = sun.misc.Unsafe.getUnsafe();
            //UNSAFE = sun.misc.Unsafe.getUnsafe();报错 不让用

            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            UNSAFE = (Unsafe)field.get(null);

            Class<?> k = UnsafeFunDemo.class;
            /**
             @see result
             */
            /**
             @see UnsafeFunDemo#set(java.lang.String)
             */
            resultAddr = UNSAFE.objectFieldOffset(k.getDeclaredField("result"));
            //UNSAFE.allocateMemory(1024*1024);
        } catch (Exception x) {
            throw new Error(x);
        }
    }

    public  boolean set(String str){
        /*  (obj == null) ? NIL : obj*/
       return UNSAFE.compareAndSwapObject(this, resultAddr, null, str);
    }

    public  String get(){
        return (String) UNSAFE.getObject(this,resultAddr);
    }



    public static void main(String[] args) {
        UnsafeFunDemo unsafeFunDemo = new UnsafeFunDemo();
        System.out.println(unsafeFunDemo.result);
        System.out.println(unsafeFunDemo.resultAddr);
        System.out.println(unsafeFunDemo.set("114"));
        System.out.println(unsafeFunDemo.get());
    }
}
